package ucsyslogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddUserNotifyMsgLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddUserNotifyMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddUserNotifyMsgLogic {
	return &AddUserNotifyMsgLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 新增通知消息
func (l *AddUserNotifyMsgLogic) AddUserNotifyMsg(in *pb.AddUserNotifyMsgReq) (*pb.AddUserNotifyMsgResp, error) {
	defer utils.RecoverPanic()

	err := l.svcCtx.UserAccountModel.Trans(l.ctx, func(ctx context.Context, tx sqlx.Session) error {
		unm := usercenter.UserNotifyMsg{
			Uid:        in.Uid,
			MsgType:    in.MsgType,
			MsgContent: in.MsgContent,
			IsRead:     dbkey.Enable,
			Title:      in.Title,
		}
		l.Logger.Infof("AddUserNotifyMsg. in: %+v", in)
		// 增加消息
		_, err2 := l.svcCtx.UserNotifyMsgModel.InsertTrans(ctx, tx, &unm)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		// 更新消息条数
		err2 = l.svcCtx.UserNotifyMsgStatModel.AddMsgCount(ctx, tx, in.Uid, 1)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		return nil
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	return &pb.AddUserNotifyMsgResp{}, nil
}
